﻿using System;
using System.Collections;
using System.Configuration;
using System.Data;
using System.Linq;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Xml;
using System.Xml.Linq;

using umbraco;
using umbraco.editorControls;

using OpenCalais;

namespace AutoTags
{
    public partial class AutoTagsTest : System.Web.UI.UserControl, umbraco.editorControls.userControlGrapper.IUsercontrolDataEditor
    {
        private string _api = "se2eg3zu8ebbfvysd52czrf2";
        public string umbracoValue;
        public System.Xml.XPath.XPathNodeIterator node;
        protected void Page_Load(object sender, EventArgs e)
        {
            if (!Page.IsPostBack)
            {
                Session["tags"] = null;
                //CheckUmbValue();
            }
            if (Page.IsPostBack)
            {
                // do more stuff here...
                //       string content = GetNodePropertyValue("bodyText");

                //_connect.GetContent(content);


                Display();
            }
            lbl_Display.Text = umbracoValue;
        }

        public object value
        {
            get { return umbracoValue; }
            set { umbracoValue = value.ToString(); }
        }

        protected void btn_Render_Click(object sender, EventArgs e)
        {
            OpenCalais.OpenCalaisConnect _connect = new OpenCalaisConnect(_api);
            //string content = GetNodePropertyValue("bodyText");

            string content = @"<p>Runway modules encapsulate specific bits of advanced functionality that are easily added to your website.</p>
<p>Once installed, Runway Modules are open source and easy to customize if you want to modify the behavior for your specific needs. <br />Because Runway modules are provided under the MIT license you are free to use and modify them any way you want, with no strings attached.</p>
<p>To add Runway modules to your website, go to the <strong>Developer</strong> section, expand the <strong>Packages</strong> item and click <strong>Install Runway modules</strong>.</p>
<p>Runwau modules are available for various kinds of navigation, a sitemap, and a contact form. The list of available Runway modules is growing rapidly and is automatically updated from a central source, always fresh and current.</p>
<p><a href=""http://umbraco.org/redir/Runway/aboutUmbraco"">Get more information</a> about the umbraco way.</p>";
            
            _connect.GetContent(content);

            gv_Tags.DataSource = _connect.Tags;
            gv_Tags.DataBind();
        }

        private void CheckUmbValue()
        {
            string toAryList = umbracoValue;
            if (toAryList == "")
                Session["tags"] = null;
            else
            {
                if (toAryList.Substring(toAryList.Length - 1, 1) == ",")
                    umbracoValue = toAryList = toAryList.Substring(0, toAryList.Length - 1);

                ArrayList list = new ArrayList();
                list.AddRange(toAryList.Split(','));
                Session["tags"] = list;
                gv_umbTags.DataSource = list;
                gv_umbTags.DataBind();
            }
        }

        private string GetNodePropertyValue(string propertyAlias)
        {
            // create an xpath that will retrieve the correct setting
            // the XML file that this runs against is in the website directory /data/umbraco.config
            string itemName = string.Format("//node[@id='{0}']/data[@alias='{1}']", Request["id"], propertyAlias);
            // default to no value
            string data = string.Empty;
            // pull an iterator from the umbraco cache, passing in our xpath
            System.Xml.XPath.XPathNodeIterator iter = umbraco.library.GetXmlNodeByXPath(itemName);
            // if matching nodes were found, interrogate only the first one
            if (iter.MoveNext())
            {
                // retrieve the setting value from the InnerXml
                data = iter.Current.InnerXml;
            }

            return (data);
        }

        protected void gv_Tags_RowCommand(object sender, GridViewCommandEventArgs e)
        {
            ArrayList tagcol;
            if (Session["tags"] != null)
                tagcol = (ArrayList)Session["tags"];
            else
                tagcol = new ArrayList();

            GridViewRow row = (GridViewRow)((LinkButton)e.CommandSource).NamingContainer;
            if (e.CommandName == "SelectItem")
            {
                if (!tagcol.Contains(row.Cells[0].Text))
                    tagcol.Add(row.Cells[0].Text);
            }
            Session["tags"] = tagcol;
            Display();
            lbl_Display.Text = umbracoValue;
        }

        protected void gv_umbTags_RowCommand(object sender, GridViewCommandEventArgs e)
        {
            ArrayList tagcol;
            if (Session["tags"] != null)
                tagcol = (ArrayList)Session["tags"];
            else
                tagcol = new ArrayList();

            GridViewRow row = (GridViewRow)((LinkButton)e.CommandSource).NamingContainer;
            if (e.CommandName == "RemItem")
            {
                if (tagcol.Contains(row.Cells[0].Text))
                    tagcol.Remove(row.Cells[0].Text);
            }

            Session["tags"] = tagcol;
            Display();
            lbl_Display.Text = umbracoValue;
        }

        private void Display()
        {
            string tags = "";
            ArrayList tagcol = (ArrayList)Session["tags"];
            if (Session["tags"] != null)
            {
                if (tagcol.Count > 0)
                {
                    foreach (string item in tagcol)
                        tags += item + ",";
                }
                if (tags.Substring(tags.Length - 1, 1) == ",")
                    tags = tags.Substring(0, tags.Length - 1);
            }
            gv_umbTags.DataSource = tagcol;
            gv_umbTags.DataBind();

            umbracoValue = tags;            
            upnl_Display.Update();
        }

        protected void btn_Own_Click(object sender, EventArgs e)
        {
            if ((tb_OwnTags.Text != null) && (tb_OwnTags.Text.Trim().Length > 0))
            {
                ArrayList tagcol;
                if (Session["tags"] != null)
                    tagcol = (ArrayList)Session["tags"];
                else
                    tagcol = new ArrayList();

                if (!tagcol.Contains(tb_OwnTags.Text))
                    tagcol.Add(tb_OwnTags.Text);


                Session["tags"] = tagcol;
                Display();
                lbl_Display.Text = umbracoValue;
            }
        }

        protected void lbClear_Click(object sender, EventArgs e)
        {
            Session["tags"] = null;
            umbracoValue = "";
            Display();
            lbl_Display.Text = umbracoValue;
        }
    }
}